package leecode

import (
	"math/rand"
)

type Solution struct {
	hashMap map[int][]int //key为数组中的元素 , value为索引
}

func Constructor398(nums []int) Solution {
	hashMap := make(map[int][]int)
	for i := 0; i < len(nums); i++ {
		hashMap[nums[i]] = append(hashMap[nums[i]], i)
	}
	return Solution{hashMap: hashMap}
}

func (this *Solution) Pick(target int) int {
	indexArr := this.hashMap[target] // 存储的索引数组
	maxNum := len(indexArr) - 1
	minNum := 0
	// 随机生成一个在索引范围内的数据
	i := minNum
	if len(indexArr) > 1 {
		i = rand.Intn(maxNum-minNum+1) + minNum
	}
	return indexArr[i]
}
